//
//  XMLParser.m
//  rss_reader
//
//  Created by Oleg Soldatoff on 4/11/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "XMLParser.h"

#define item          @"item"
#define title         @"title"
#define description   @"description"
#define pubDate       @"pubdate"
#define url           @"link"
#define href          @"href"


@implementation XMLParser
@synthesize arrayWithItems = _arrayWithItems;
@synthesize arrayWithFeeds = _arrayWithFeeds;
@synthesize inItem;
@synthesize itemTitle = _itemTitle;
@synthesize itemDescription = _itemDescription;
@synthesize itemDate = _itemDate;
@synthesize itemUrl = _itemUrl;
@synthesize currentProperty = _currentProperty;


+ (NSArray*) arrayWithItems:(NSData *)data {
  
  XMLParser *xmlParser = [[[XMLParser alloc] init]autorelease];
  [xmlParser parseRSS: data parseError:nil];
  NSMutableArray *tmp = [[xmlParser.arrayWithItems retain]autorelease];
  
  return tmp;
  
  
}
+ (NSArray*) arrayWithFeeds:(NSData *)data {

  XMLParser *xmlParser = [[[XMLParser alloc] init]autorelease];
  [xmlParser convertFeeds: data];
  NSMutableArray *tmp = [[xmlParser.arrayWithFeeds retain]autorelease];
  
  return tmp;


}


- (void) convertFeeds: (NSData *)data {
  
  NSString *linker;
  NSError *error = NULL;
  NSString *hrefer;
  NSString *titler;
  //NSMutableString *xmlForParser;
  //xmlForParser = [[[NSMutableString alloc]init ]autorelease];
  
  NSString *xmlCheck = [[[NSString    alloc] initWithData:data  encoding:NSUTF8StringEncoding] autorelease];
  /*if (nil == xmlCheck) {
    xmlCheck = [[[NSString    alloc] initWithData:data  encoding:NSWindowsCP1251StringEncoding] autorelease];
  }*/
  NSScanner *theScanner = [NSScanner scannerWithString:xmlCheck];

  self.arrayWithFeeds = [[[NSMutableArray alloc] init]autorelease]; 
  
  while ([theScanner isAtEnd] == NO)  
  {
    
    if ([theScanner scanUpToString:@"<link" intoString:NULL] && 
        [theScanner scanUpToString:@">" intoString:&linker] ) 
    {
      
      NSScanner *theScannerLinker = [NSScanner scannerWithString:linker];
      NSRegularExpression *regexAppRssXml = [NSRegularExpression regularExpressionWithPattern:@"application.rss.xml"
                                                                 options:NSRegularExpressionCaseInsensitive
                                                                 error:&error];
      
      NSUInteger numberOfRSSXML = [regexAppRssXml numberOfMatchesInString:linker
                                                  options:0
                                                  range:NSMakeRange(0, [linker length])];        
      if ( numberOfRSSXML > 0) 
      {
        
        theScannerLinker.scanLocation = 0;
        while ([theScannerLinker isAtEnd] == NO) 
        {
          [theScannerLinker scanUpToString:@"href=\"" intoString:NULL];
          [theScannerLinker scanString:@"href=\"" intoString:NULL];
          [theScannerLinker scanUpToString:@"\"" intoString:&hrefer]; 
        }
        
        theScannerLinker.scanLocation = 0;
        while ([theScannerLinker isAtEnd] == NO) 
        {
          [theScannerLinker scanUpToString:@"title=\"" intoString:NULL];
          [theScannerLinker scanString:@"title=\"" intoString:NULL];
          [theScannerLinker scanUpToString:@"\"" intoString:&titler]; 
          
        }
        
        [self.arrayWithFeeds addObject: [self dictionaryWithFeed:titler feedUrl:hrefer]]; 
       // [xmlForParser appendString:[NSString stringWithFormat:@"<link rel=\"alternate\" type=\"application/rss+xml\" title=\"%@\" href=\"%@\" >",titler, hrefer ]];
       
      }
    }
  }
  NSLog(@"Found feeds %d", [self.arrayWithFeeds count]);
} 


- (NSDictionary *) dictionaryWithFeed: (NSString* ) feedTitle feedUrl: (NSString *) feedLink {
  
  return [NSDictionary dictionaryWithObjectsAndKeys:
          feedTitle, title,
          feedLink, href,
          nil];
  
}





- (id)init {
  
  self = [super init];
  if (self) {
   
  }
  return self;
}


- (void)dealloc {
 
  [_arrayWithItems release];
  _arrayWithItems = nil;
  [_arrayWithFeeds release];
  _arrayWithFeeds = nil;
  [_itemTitle release];
  _itemTitle = nil;
  [_itemDescription release];
  _itemTitle = nil;
  [_itemDate release];
  _itemDate = nil;
  [_itemUrl release];
  _itemUrl = nil;
  [_currentProperty release];
  _currentProperty = nil;
  [super dealloc];
  
}


- (NSArray *)parseRSS:(NSData *)data parseError:(NSError **)err {
  
  NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
  self.arrayWithItems = [[[NSMutableArray alloc] init]autorelease]; 
 
  [parser setDelegate:self]; // The parser calls methods in this class
  [parser setShouldProcessNamespaces:NO]; // We don't care about namespaces
  [parser setShouldReportNamespacePrefixes:NO]; //
  [parser setShouldResolveExternalEntities:NO]; // We just want data, no other stuff
  
  [parser parse]; // Parse that data..
  
  if (err && [parser parserError]) {
    *err = [parser parserError];
  }
  
  [parser release];
  return self.arrayWithItems;
}
 

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
  
  
  
  if ( [[elementName lowercaseString] isEqualToString:item] == YES) {
    
    self.inItem = YES;
    
  } else if (self.inItem == YES) {
    
    if ( [[elementName lowercaseString] isEqualToString:title] == YES || 
         [[elementName lowercaseString] isEqualToString:description] == YES ||
         [[elementName lowercaseString] isEqualToString:pubDate] == YES || 
         [[elementName lowercaseString] isEqualToString:url] == YES ) {
      
           self.currentProperty = [[[NSMutableString alloc] init] autorelease];
    }

  }
  
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
  
  if (self.inItem == YES) {

    [self.currentProperty appendString:string];
    
  }
 
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
  
  if ( self.inItem == YES &&
      [[elementName lowercaseString] isEqualToString:item] != YES ) {
    
      if ( [[elementName lowercaseString] isEqualToString:title] == YES ) {
        self.itemTitle =  self.currentProperty;
      } else if ( [[elementName lowercaseString] isEqualToString:url] == YES) {
      self.itemUrl =  self.currentProperty;
      } else if ([[elementName lowercaseString] isEqualToString:description] == YES){
       self.itemDescription =  self.currentProperty;
      } else if ([[elementName lowercaseString] isEqualToString:pubDate] == YES){
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]autorelease];
        [dateFormatter setDateFormat:@"EEE, dd LLL yyyy HH:mm:ss zzz"];
        NSDate *myDate = [dateFormatter dateFromString:self.currentProperty];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        self.itemDate =  [dateFormatter stringFromDate:myDate];
      }

  } else if (self.inItem == YES &&
             [[elementName lowercaseString] isEqualToString:item] == YES) {
    
    self.inItem = NO;
    [self.arrayWithItems addObject: [self dictionaryWithItem]];
    
  }
    self.currentProperty = nil;
  
}

- (NSDictionary *) dictionaryWithItem {
  
  return [NSDictionary dictionaryWithObjectsAndKeys:
                        self.itemTitle, title, 
                        self.itemUrl, url, 
                        self.itemDescription, description, 
                        self.itemDate, pubDate, 
                        nil];

}



@end
